/**
 * 短信发送工具模块
 * 支持阿里云短信服务
 */

const Core = require('@alicloud/pop-core');

// 创建阿里云短信客户端
const createSMSClient = () => {
  const accessKeyId = process.env.ALIYUN_SMS_ACCESS_KEY_ID;
  const accessKeySecret = process.env.ALIYUN_SMS_ACCESS_KEY_SECRET;

  if (!accessKeyId || !accessKeySecret) {
    throw new Error('阿里云短信配置缺失，请检查.env文件中的ALIYUN_SMS_ACCESS_KEY_ID和ALIYUN_SMS_ACCESS_KEY_SECRET');
  }

  return new Core({
    accessKeyId,
    accessKeySecret,
    endpoint: 'https://dysmsapi.aliyuncs.com',
    apiVersion: '2017-05-25'
  });
};

/**
 * 发送短信验证码
 * @param {string} phone - 手机号
 * @param {string} code - 验证码
 * @returns {Promise<{success: boolean, message?: string}>} 发送结果
 */
async function sendSMS(phone, code) {
  // 如果未启用短信服务，返回成功（开发模式）
  if (process.env.SMS_ENABLED !== 'true') {
    console.log(`📱 [开发模式] 短信验证码: ${code} → ${phone}`);
    return { success: true, message: '开发模式：验证码已在日志中显示' };
  }

  try {
    const client = createSMSClient();
    const params = {
      PhoneNumbers: phone,
      SignName: process.env.ALIYUN_SMS_SIGN_NAME,
      TemplateCode: process.env.ALIYUN_SMS_TEMPLATE_CODE,
      TemplateParam: JSON.stringify({ code })
    };

    const requestOption = {
      method: 'POST'
    };

    const result = await client.request('SendSms', params, requestOption);

    console.log('📱 短信发送结果:', result);

    // 检查发送结果
    if (result.Code === 'OK') {
      console.log(`✅ 短信发送成功: ${phone}`);
      return { success: true, message: '短信发送成功' };
    } else {
      console.error(`❌ 短信发送失败: ${result.Message}`);
      return {
        success: false,
        message: result.Message || '短信发送失败'
      };
    }
  } catch (error) {
    console.error('❌ 短信发送异常:', error);
    return {
      success: false,
      message: error.message || '短信发送失败'
    };
  }
}

module.exports = {
  sendSMS
};

